package com.quectel.cms.controller.devicepatrol;


import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.devicepatrol.dto.DevicePatrolEventReportDto;
import com.quectel.core.module.devicepatrol.service.DevicePatrolEventReportService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:06
 */
@RestController
@RequestMapping("devicePatrolEventReport")
@Tag(name = "DevicePatrolEventReportController", description = "设备巡检事件上报相关api")
public class DevicePatrolEventReportController extends BaseController {

    @DubboReference
    private DevicePatrolEventReportService devicePatrolEventReportService;

    /**
     * 列表
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "devicePatrolEventReport:exportExcel")
    @Operation(summary = "导出巡检任务详情")
    public void exportExcel(HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));
        Map<String, Object> params = request.getParams();

        super.fillAuthorityData(params);

        List<DevicePatrolEventReportDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<DevicePatrolEventReportDto> list = devicePatrolEventReportService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"所属小区", "任务名称", "设备IMEI", "设备名称", "设备地址", "巡检照片", "巡检描述", "巡检结果", "跳检原因", "工单编号", "巡检人", "创建时间", "完成时间"};
        List<String[]> dataList = new ArrayList<>();
        for (DevicePatrolEventReportDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageName();
            item[1] = data.getTaskName();
            item[2] = data.getImei();
            item[3] = data.getDeviceName();
            item[4] = data.getInstallAddress();
            item[5] = data.getSnapshotImg();
            item[6] = data.getDetail();
            item[7] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PATROL_STATUS, String.valueOf(data.getStatus()));
            item[8] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.REASONS_FOR_SKIP_INSPECTION, String.valueOf(data.getSkipCheckReasonType()));
            item[9] = data.getWorkOrderNo();
            item[10] = data.getReportUsername();
            item[11] = data.getCreateTime() == null ? "" : DateUtils.format(data.getCreateTime(), DateUtils.FormatType.COMMON);
            item[12] = data.getCompleteTime() == null ? "" : DateUtils.format(data.getCompleteTime(), DateUtils.FormatType.COMMON);
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "巡检设备上报", headers, dataList, "巡检设备上报");

    }


    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "devicePatrolEventReport:list")
    @Operation(summary = "设备巡检事件上报的分页查询列表")
    public Response<Page<DevicePatrolEventReportDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = devicePatrolEventReportService.queryTotal(request.getParams());

        List<DevicePatrolEventReportDto> list = null;
        if (total > 0) {
            list = devicePatrolEventReportService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<DevicePatrolEventReportDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<DevicePatrolEventReportDto>>ok().wrap(page);
    }


    /**
     * 编辑反显查询
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "devicePatrolEventReport:edit")
    @Operation(summary = "查询单条设备巡检事件上报记录")
    public Response<DevicePatrolEventReportDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (devicePatrolEventReportService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        DevicePatrolEventReportDto devicePatrolEventReportDto = devicePatrolEventReportService.selectById(id);

        return Response.<DevicePatrolEventReportDto>ok().wrap((devicePatrolEventReportDto));
    }

    /**
     * 信息
     * 权限:可以查看task就可以查看report
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "devicePatrolTask:info")
    @Operation(summary = "查询单条设备巡检事件上报记录")
    public Response<DevicePatrolEventReportDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (devicePatrolEventReportService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        DevicePatrolEventReportDto devicePatrolEventReportDto = devicePatrolEventReportService.selectById(id);

        return Response.<DevicePatrolEventReportDto>ok().wrap((devicePatrolEventReportDto));
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "devicePatrolEventReport:edit")
    @Operation(summary = "保存单条设备巡检事件上报记录")
    public Response<Object> save(@RequestBody @Validated DevicePatrolEventReportDto devicePatrolEventReportDto) {

        //填充基础数据
        fillSaveCommonData(devicePatrolEventReportDto);

        devicePatrolEventReportService.save(devicePatrolEventReportDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @RequirePermissions(values = "devicePatrolEventReport:edit")
    @Operation(summary = "修改单条设备巡检事件上报记录")
    public Response<Object> update(@RequestBody @Validated DevicePatrolEventReportDto devicePatrolEventReportDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(devicePatrolEventReportDto.getId()));
        if (devicePatrolEventReportService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(devicePatrolEventReportDto);

        devicePatrolEventReportService.updateById(devicePatrolEventReportDto);

        return Response.ok();
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "devicePatrolEventReport:delete")
    @Operation(summary = "批量删除存在的设备巡检事件上报记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (devicePatrolEventReportService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        devicePatrolEventReportService.deleteBatch(ids);

        return Response.ok();
    }
}
